//
//  ContactViewController.m
//  通讯录-02
//
//  Created by 伍银荣 on 2021/6/29.
//  Copyright © 2021 com.example. All rights reserved.
//

#import "ContactViewController.h"
#import "AddViewController.h"
#import "Contact.h"
#import "EditViewController.h"

#define kFilePath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0] stringByAppendingPathComponent:@"contacts.data"]

@interface ContactViewController ()<AddViewControllerDelegate, EditViewControllerDelegate>
@property (nonatomic, strong) NSMutableArray *contacts;
@end

@implementation ContactViewController

-(NSMutableArray *)contacts {
    if (!_contacts) {
        _contacts = [NSMutableArray array];
    }
    return _contacts;
}

//注销按钮的点击事件
- (IBAction)loginoutItemClicked:(id)sender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您需要注销吗?" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"注销" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
       //点击注销按钮后的操作
        [self.navigationController popViewControllerAnimated:YES];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.tableFooterView = [UIView new];
    
    //解档添加联系人信息
    self.contacts = [NSKeyedUnarchiver unarchiveObjectWithFile:kFilePath];
    NSLog(@"---contacts = %@",self.contacts);
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.destinationViewController isKindOfClass:[AddViewController class]]) {
        AddViewController *addVC = segue.destinationViewController;
        addVC.delegate = self;
    } else {
        EditViewController *editVC = segue.destinationViewController;
        editVC.delegate = self;
        NSIndexPath *idxPath = [self.tableView indexPathForSelectedRow];
        editVC.contact = self.contacts[idxPath.row];
    }
}

//-(void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
//    [self.tableView reloadData];
//}

#pragma mark - AddViewControllerDelegate
- (void)addViewController:(AddViewController *)addViewController andNameText:(NSString *)nameText andNumberText:(NSString *)numberText {
    Contact *contact = [[Contact alloc]init];
    contact.name = nameText;
    contact.number = numberText;
    [self.contacts addObject:contact];
    [self.tableView reloadData];
    
    BOOL success = [NSKeyedArchiver archiveRootObject:self.contacts toFile:kFilePath];
    if (success) {
        NSLog(@"归档成功");
    } else {
        NSLog(@"归档失败");
    }
}

#pragma mark - EditViewControllerDelegate
-(void)editViewController:(EditViewController *)editViewController {
    //因为模型数据是传过去的,都是同一个对象,所以不用带其他的参数,只需要刷新一下tableView就好了
    [self.tableView reloadData];
    BOOL success = [NSKeyedArchiver archiveRootObject:self.contacts toFile:kFilePath];
    if (success) {
        NSLog(@"归档成功");
    } else {
        NSLog(@"归档失败");
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
     return self.contacts.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"contact_cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID  forIndexPath:indexPath];
    cell.textLabel.text = [self.contacts[indexPath.row] name];
    cell.detailTextLabel.text = [self.contacts[indexPath.row] number];
    return cell;
}

//是否允许左滑
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

//左滑删除操作
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"左滑删除操作");
    //先删除模型再删除这一行cell
    [self.contacts removeObjectAtIndex:indexPath.row];
    [self.tableView reloadData];
}


//自定义左滑按钮的title
//- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return @"删除";  //默认是delete
//}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
